package com.jiji.miaosha.controller;

import com.jiji.miaosha.error.BusinessException;
import com.jiji.miaosha.error.EmBusinessError;
import com.jiji.miaosha.service.OrderService;
import com.jiji.miaosha.service.model.OrderModel;
import com.jiji.miaosha.service.model.UserModel;
import com.jiji.miaosha.util.ResultVOUtil;
import com.jiji.miaosha.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/order")
@CrossOrigin(allowCredentials = "true", allowedHeaders = "*")
public class OrderController extends BaseController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private HttpServletRequest httpServletRequest;

    //封装下单信息
    @RequestMapping(value = "/createorder", method = RequestMethod.POST, consumes = {CONTENT_TYPE_FORMED})
    private ResultVO createOrder(@RequestParam(name = "itemId") Integer itemId,
                                 @RequestParam(name = "amount") Integer amount,
                                 @RequestParam(name = "promoId", required = false) Integer promoId) {
        Boolean isLogin = (Boolean) httpServletRequest.getSession().getAttribute("IS_LOGIN");
        if (isLogin == null || !isLogin) {
            throw new BusinessException(EmBusinessError.USER_NOT_LOGIN,"用户未登录，不能下单");
        }
        UserModel userModel = (UserModel) httpServletRequest.getSession().getAttribute("LOGIN_USER");

        OrderModel orderModel = orderService.createOrder(userModel.getId(), itemId, promoId, amount);
        return ResultVOUtil.success();
    }
}
